<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use Carbon\Carbon;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\library\Partner as PartnerLib;

/**
 * 合伙人
 *
 * @icon fa fa-circle-o
 */
class Partner extends Backend
{

    /**
     * Partner模型对象
     * @var \app\admin\model\user\Partner
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Partner;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("verifyStatusList", $this->model->getVerifyStatusList());
        $this->view->assign("isFileSignedList", $this->model->getIsFileSignedList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->where($where)->paginate($limit);
            $rows = $list->items();
            $partnerLib = new PartnerLib();
            foreach ($rows as $r) {
                $partnerLib->updateParentId($r->id);
            }

            $list = $this->model
                ->with(['user', 'level', 'dre', 'parent'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function readonly()
    {
        $partnerId = input('get.partnerid');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'level'])
                ->where('find_in_set('.$partnerId.', dre_id_path)')
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!$params['level_id']) {
            $params['level_id'] = null;
        }
        if (!$params['parent_id']) {
            $params['parent_id'] = null;
            $params['parent_id_path'] = null;
        } else {
            $params['parent_id_path'] = \app\admin\model\user\Partner::getTheParentPath($params['parent_id']);
        }

        if (!$params['dre_id']) {
            $params['dre_id'] = null;
        } else {
            $params['dre_id_path'] = \app\admin\model\user\Partner::getDreParentPath($params['parent_id']);
        }
        // 生成partner_account
        $userId = $params['user_id'];
        $user = \app\admin\model\User::get($userId);
        $params['partner_account'] = $user->username; // 三号合一

        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // 把石头的值保存到user表
            $user = \app\admin\model\User::get($userId);
            $user->green_stone_amount = $params['green_stone_amount'];
            $user->blue_stone_amount = $params['blue_stone_amount'];
            $user->red_stone_amount = $params['red_stone_amount'];
            $user->is_partner = 1; //设置为合伙人
            $user->save();

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!$params['level_id']) {
            $params['level_id'] = null;
        }
        if (!$params['parent_id']) {
            $params['parent_id'] = null;
            $params['parent_id_path'] = null;
        } else {
            $params['parent_id_path'] = \app\admin\model\user\Partner::getTheParentPath($params['parent_id']);
        }

        if (!$params['dre_id']) {
            $params['dre_id'] = null;
        }
        if (in_array($params['verify_status'], [2,3])) {
            $params['verify_time'] = Carbon::now()->toDateTimeString();
        }
        if (2 == $params['verify_status'] and 1 == $row->is_file_signed and 1 == $row->status) {
            $params['status'] = 2; // 如果用户认证成功同时文件有签，用户就是正常态
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            // 把石头的值保存到user表
            $user = \app\admin\model\User::get($row->user_id);
            $user->green_stone_amount = $params['green_stone_amount'];
            $user->blue_stone_amount = $params['blue_stone_amount'];
            $user->red_stone_amount = $params['red_stone_amount'];
            $user->save();

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                $user = \app\admin\model\User::get($item->user_id);
                $user->is_partner = 0;
                $user->save();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


}
